<template>
  <BasicModal
    width="70%"
    :title="t('component.upload.preview')"
    class="upload-preview-modal"
    v-bind="$attrs"
    @register="register"
    :showOkBtn="false"
  >
    <!-- <FileList :dataSource="fileListRef" :columns="columns" :actionColumn="actionColumn" /> -->
    <!-- <div style="height: 500px"> </div> -->
    <!-- <BasicTable
      :dataSource="fileListRef"
      :columns="columns"
      :actionColumn="actionColumn"
      style="height: 100%"
      :maxHeight="400"
      :canResize="true"
    /> -->
    <div style="overflow: hidden; width: 100%; height: 100%">
      <VxeBasicTable ref="tableRef" v-bind="gridOptions" :data="fileListRef">
        <template #action="{ row, rowIndex }">
          <TableAction outside :actions="createActions(row, rowIndex)" />
        </template>
      </VxeBasicTable>
    </div>
  </BasicModal>
</template>
<script lang="ts" setup>
import { watch, ref, h, reactive } from 'vue';
import FileList from './FileList.vue';
import { BasicTable, useTable, BasicColumn, TableAction, ActionItem } from '@/components/Table';
import { BasicModal, useModalInner } from '@/components/Modal';
import { handleFnKey, previewProps } from '../props';
import { BaseFileItem, FileBasicColumn, PreviewFileItem } from '../types/typing';
import { downloadByUrl } from '@/utils/file/download';
import { createPreviewColumns, createPreviewActionColumn } from './data';
import { useI18n } from '@/hooks/web/useI18n';
import { isArray, isFunction } from '@/utils/is';
import { useMessage } from '@/hooks/web/useMessage';
import { buildUUID } from '@/utils/uuid';
import {
  BasicTableProps,
  VxeBasicTable,
  VxeGridInstance,
  VxeGridListeners,
} from '@/components/VxeTable';

const { createMessage } = useMessage();
import util from '@/utils/util';
const props = defineProps(previewProps);

const emit = defineEmits(['list-change', 'register', 'delete']);

let columns: BasicColumn[] | FileBasicColumn[] = createPreviewColumns();
let actionColumn = [];
const actionColumns = ref([]);
const [register] = useModalInner();
const { t } = useI18n();

const fileListRef = ref<BaseFileItem[] | Array<any>>([]);

const tableRef = ref<VxeGridInstance>();

watch(
  () => props.previewColumns,
  () => {
    if (Array.isArray(props.previewColumns) && props.previewColumns.length) {
      columns = props.previewColumns;
      // actionColumn = null;
    } else if (isFunction(props.previewColumns)) {
      columns = props.previewColumns({ handleRemove, handleAdd });
    } else {
      columns = createPreviewColumns();
      actionColumn = createPreviewActionColumn({
        handleRemove,
        handleDownload,
        handleSortUp,
        handleSortDown,
      });
    }
    actionColumns.value = actionColumn.customRender;
    //  console.log("----columns:", columns);
  },
  { immediate: true },
);

watch(
  () => props.value,
  (value) => {
    if (!isArray(value)) value = [];
    if (props.beforePreviewData) {
      value = props.beforePreviewData(value) as any;
      fileListRef.value = value;
      return;
    }
    fileListRef.value = value
      .filter((item) => !!item)
      .map((item) => {
        if (typeof item != 'object') {
          console.error('return value should be object');
          return;
        }
        return {
          uid: item?.uid,
          url: item?.url,
          sort: item.sort,
          type: item?.url?.split('.').pop() || '',
          name: item?.url?.split('/').pop() || '',
        };
      });
    //  console.log("----fileListRef:", fileListRef.value);
  },
  { immediate: true },
);

const gridOptions = reactive<BasicTableProps>({
  id: 'VxeTable',
  keepSource: true,
  editConfig: { trigger: 'click', mode: 'cell', showStatus: true },
  showOverflow: true,
  // size: 'mini',
  height: 'auto',
  data: fileListRef.value,
  columns,
  toolbarConfig: {
    enabled: false,
  },
  formConfig: {
    enabled: false,
  },
  proxyConfig: {
    enabled: false,
  },
});

watch(
  () => fileListRef.value,
  (value) => {
    if (!isArray(value)) value = [];
    if (tableRef.value) {
      tableRef.value.loadData(value);
    }
  },
  { immediate: true },
);

const createActions = (record, index) => {
  let actions: ActionItem[] = [
    {
      label: t('component.upload.del'),
      color: 'error',
      onClick: handleRemove.bind(null, {
        record,
        uidKey: 'uid',
        valueKey: 'url',
      }),
    },
    {
      label: t('component.upload.download'),
      onClick: handleDownload.bind(null, record),
    },
    {
      label: '上移',
      onClick: handleSortUp.bind(null, record, index),
    },
    {
      label: '下移',
      onClick: handleSortDown.bind(null, record, index),
    },
  ];

  return actions;
};

// 删除
function handleRemove(obj: Record<handleFnKey, any>) {
  let { record = {}, valueKey = 'url', uidKey = 'uid' } = obj;
  const index = fileListRef.value.findIndex((item) => item[uidKey] === record[uidKey]);
  if (index !== -1) {
    const removed = fileListRef.value.splice(index, 1);
    emit('delete', removed[0][uidKey]);
    emit('list-change', fileListRef.value, valueKey);
  }
}
// 添加
function handleAdd(obj: Record<handleFnKey, any>) {
  let { record = {}, valueKey = 'url', uidKey = 'uid' } = obj;
  const { maxNumber } = props;
  if (fileListRef.value.length + fileListRef.value.length > maxNumber) {
    return createMessage.warning(t('component.upload.maxNumber', [maxNumber]));
  }
  record[uidKey] = record[uidKey] ?? buildUUID();
  fileListRef.value = [...fileListRef.value, record];
  emit('list-change', fileListRef.value, valueKey);
}
// 下载
function handleDownload(record: PreviewFileItem) {
  const { url = '' } = record;
  downloadByUrl({ url });
}

function beforeEditSubmit({ record, index, key, value }) {
  let list = fileListRef.value;
  // list[index] = record;

  list.sort(function (a, b) {
    return a.sort - b.sort;
  });
  fileListRef.value = list;
  emit('list-change', fileListRef.value);

  // console.log('单元格数据正在准备提交', { record, index, key, value });
}

//上移
function handleSortUp(record: PreviewFileItem, index) {
  // console.log('---上移index', index);
  if (index == 0) {
    createMessage.warning('已经处于最顶部，无法在往上移动了！');
    return false;
  }
  let list = fileListRef.value;
  let old = util.copy(list[index - 1].sort);
  list[index - 1].sort = list[index].sort;
  list[index].sort = old;
  list.sort(function (a, b) {
    return a.sort - b.sort;
  });
  fileListRef.value = list;
  emit('list-change', fileListRef.value);
}
//下移
function handleSortDown(record: PreviewFileItem, index) {
  // console.log('---下移index', index);
  if (fileListRef.value.length == index + 1) {
    createMessage.warning('已经处于最低部，无法在往下移动了！');
    return false;
  }
  let list = fileListRef.value;
  let old = util.copy(list[index + 1].sort);
  list[index + 1].sort = list[index].sort;
  list[index].sort = old;
  list.sort(function (a, b) {
    return a.sort - b.sort;
  });
  fileListRef.value = list;
  emit('list-change', fileListRef.value);
}
</script>
<style lang="less">
.upload-preview-modal {
  .ant-upload-list {
    display: none;
  }

  .ant-table-wrapper .ant-spin-nested-loading {
    padding: 0;
  }
}
</style>
